package jyan.sango.crazy.core.xml;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jyan.sango.crazy.core.debug.DEBUG;
import jyan.sango.crazy.core.debug.SangoException;
import jyan.sango.crazy.core.player.Role;

import org.dom4j.Element;

public class ReadRole {
	// 配置文件名
	private static final String filerole = "role.xml";
	public static List<?> getRolesWithFileName(String filename) throws SangoException {
		List<Role> rolelist = new ArrayList<Role>();	
		List<?> list = ReadFile.getElementList(getRoleFile(filename));
		String str = null;
		Element data = null;
		Iterator<?> subitr = null;
		int i = 0;
		while (true) {
			Role role = new Role();
			data = (Element) list.get(i);
			DEBUG.Print(list.toString());
			subitr = data.elementIterator();
			DEBUG.Print(data.attribute("index").getName());
			str = data.attribute("index").getName();

			if (str.equals("index")) {
				str = data.attribute("index").getText();
				DEBUG.Print(str);
				role.setPlayerIndex(Integer.parseInt(str));
				i = Integer.parseInt(str);
				if (i != -1) {
					++i;
				} else {
					break;
				}
			}
			while (subitr.hasNext()) {
				data = (Element) subitr.next();
				str = data.getName();
				DEBUG.Print(str);
				str = data.getText();
				role = setToRole(role, str, data.getName());
			}
			rolelist.add(role);
		}
		return (List<?>) rolelist;
	}
	
	private static Role setToRole(Role role, String str, String flag) {
		str = str.trim();
		if (flag.equals("name")) {
			DEBUG.Print(str);
			role.setRoleNmae(str);
		} else if (flag.equals("life")) {
			DEBUG.Print(str);
			role.setUpperLife(Integer.parseInt(str));
		} else if (flag.equals("force")) {
			DEBUG.Print(str);
			role.setForce(Integer.parseInt(str));
		} else if (flag.equals("sex")) {
			DEBUG.Print(str);
			role.setSex(Integer.parseInt(str));
		} else if (flag.equals("skills")) {
			DEBUG.Print(str);
			role.setSkillNumbers(Integer.parseInt(str));
		} else {

		}
		return role;
	}
	
	private static File getRoleFile(final String filename) {
		String tmpfilename = null;
		if (filename != null) {
			tmpfilename = filename;
		} else {
			tmpfilename = filerole;
		}
		File f = new File(tmpfilename);
		return f;
	}
}
